<?php

namespace api\libs\event\components;

use api\components\RequestClient;
use api\models\ChangeList;
use api\modules\app\models\MetaArea;
use api\modules\app\models\TaskRecord;
use api\modules\app\models\UserSignin;
use api\modules\app\models\UserSigninLink;
use Yii;
use api\libs\event\models\EventLog;
use yii\base\Component;
use api\libs\event\models\Event;
use api\components\Notification;
use yii\db\Exception;

/**
 * 事件监听类用于记录地址信息
 *
 * @author tony-liu
 * @date 2020-02-11
 * @access public
 */
class SigninListener extends Component {

    /**
     * consultant save signin
     * @param array $event 例如
     * array(
     *   'name'=> 'campaign.create',
     *   'sender' => Object,
     *   'data' => array(
     *      'user_id' => '1',
     *      'type' => '1',
     *      'lat' => '31.29064',
     *      'lng' => '121.455761',
     *      'address' => '测试地址',
     * ))
     */
    public static function onSaveSignin($event)
    {
        $sender = $event->sender;
        $data = $event->data;
        if (isset($sender['id']) && !empty($sender['lng']) && !empty($sender['lat'])) {
            self::saveUserSignin($sender, $data);
        } else {
            Yii::error('Missing Parameters.');
        }
    }
    
    /**
     * 保存点位数据
     * @param $sender
     * @param $data
     */
    public static function saveUserSignin($sender, $data)
    {
        $model = new UserSignin();
        $model->user_id = Yii::$app->user->id;
        $model->lat     = (double)$sender['lat'];
        $model->lng     = (double)$sender['lng'];
        $model->created_at = time();
        $model->address = isset($sender['address'])?$sender['address']:'';
        if ($model->save()) {
            isset($data['join_table']) && self::saveJoinData($data['join_table'],$model->id,$sender['id']);
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 保存关联数据
     * @param $joinTable
     * @param $iSigninId
     * @param $iJoinTableId
     */
    public static function saveJoinData($joinTable,$iSigninId,$iJoinTableId)
    {
        $model = new UserSigninLink();
        $model->signin_id   = $iSigninId;
        $model->join_table  = $joinTable;
        $model->join_id     = $iJoinTableId;
        $model->save();
        return true;
    }
}
